//
//  BKUserRealNameAuthController.m
//  bestkeep
//
//  Created by windCould on 16/12/1.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKUserRealNameAuthController.h"
#import "BKRealAuthFailReasonView.h"
#import "BkRealNamePersonalInfoView.h"
#import "BKUserChoosePhotosView.h"
#import "BKUserSectionHeaderView.h"
#import "BKMyCommon.h"
#import "TZImagePickerController.h"
#import "BKUserUnitRequestAPI.h"
#import "BKUserCodeFormat.h"
#import "BKUserRequestUrl.h"
@interface BKUserRealNameAuthController ()<UIScrollViewDelegate,BKUserChoosePhotosViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate,UINavigationControllerDelegate,BkRealNamePersonalInfoViewDelegate,UIGestureRecognizerDelegate>

@property (nonatomic,strong)UIScrollView * bGScrowView;
@property (nonatomic,strong)BkRealNamePersonalInfoView * personalInfoView;
@property (nonatomic,strong)BKUserChoosePhotosView * choosePhotoView;
@property (nonatomic,strong)BKUserSectionHeaderView * personalInfHeaderView;
@property (nonatomic,strong)BKUserSectionHeaderView * photosHeaderView;
@property (nonatomic,strong)BKRealAuthFailReasonView * authReasonViews;
@property (nonatomic,strong)UIButton * commitBtn;

@property (nonatomic,strong) UIImage * rigthImg;
@property (nonatomic,strong) UIImage * leftImg;
@property (nonatomic,copy)NSString  * leftImgstr;
@property (nonatomic,copy)NSString  * rightImgStr;

@property (nonatomic,assign)NSInteger  CurrentTag;

@property (nonatomic,strong)UIView * bgView;
@property (nonatomic,strong)UIDatePicker * datePick;

@property (nonatomic,assign)BOOL  isForever;
@property (nonatomic,strong)UIView * bgView1;


@end


@implementation BKUserRealNameAuthController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"实名认证";
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.isForever = NO;
    self.view.backgroundColor = ThemeBackgroundColor;
    [self setUpViews];
    
}


#pragma mark ===================BkRealNamePersonalInfoViewDelegate===========

-(void)bkRealNamePersonalInfoView:(BkRealNamePersonalInfoView *)realNamePersonalInfoView avalableTimeValue:(UILabel *)timeLable
{
    [self.view endEditing:YES];
    __weak typeof(self) weakSelf = self;
    self.bgView1.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        weakSelf.bgView .frame = CGRectMake(0, ScreenHeight-340,SCREENWIDTH, 340);
        
    } completion:^(BOOL finished) {
        
        
    }];
}

-(void)bkRealNamePersonalInfoView:(BkRealNamePersonalInfoView *)realNamePersonalInfoView setForevreTime:(BOOL)isForever
{
    self.isForever = isForever;
}

#pragma mark =========================Function===============================

//提交申请
-(void)commitBtnClick
{
    BOOL result = [self dataIsRightFormat];
    
    if (!result) {
        
        return;
    }
    
    NSMutableDictionary * paraDict = [NSMutableDictionary dictionary];
    [paraDict setObject:@"3" forKey:@"source"];
    [paraDict setObject:_personalInfoView.userRealNameStr forKey:@"realName"];
    if (self.isForever) {
        
        [paraDict setObject:@"1" forKey:@"datetimeMax"];
        [paraDict setObject:@"永久" forKey:@"idcardDeadlineDate"];
    } else {
        
        [paraDict setObject:@"1" forKey:@"datetimeMax"];
        [paraDict setObject:_personalInfoView.availableTimeStr forKey:@"idcardDeadlineDate"];
    }
    
    [paraDict setObject:_personalInfoView.identifiCardIdStr forKey:@"certypeNumber"];
    [paraDict setObject:_personalInfoView.deatailAddressStr forKey:@"address"];
    [paraDict setObject:self.leftImgstr forKey:@"pic1"];
    [paraDict setObject:self.rightImgStr forKey:@"pic2"];
    
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI upLoadRealNameAuthPersonalInfoWithInfoDict:paraDict resultBlock:^(id obj, NSError *error) {
        
        [BKIndicationView dismiss];
        if (obj) {
            
            BKUserRequestResultModel * result = obj;
            if ([result.success isEqualToString:@"1"]) {
                
                NSLog(@"实名认证成功:%@",result.msg);
                [HUD showSuccessMessage:result.msg];
                [self.navigationController popToRootViewControllerAnimated:YES];
                
            } else {
                
                [HUD showErrorMessage:result.msg];
                NSLog(@"实名认证:%@",result.msg);
            }
        } else {
            
            NSLog(@"实名认证网络请求失败");
            [HUD showErrorMessage:@"实名认证网络请求失败"];
        }
        
    }];
    
}


-(BOOL)dataIsRightFormat
{
    
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:_personalInfoView.userRealNameStr]) {
        
        NSLog(@"请正确输入用户名");
        [HUD showErrorMessage:@"请正确输入用户名"];
        return NO;
    }
    
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:_personalInfoView.identifiCardIdStr]) {
        
        NSLog(@"请正确输入身份证号");
        [HUD showErrorMessage:@"请正确输入身份证号"];
        return NO;
    }
    
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:_personalInfoView.availableTimeStr]) {
        
        NSLog(@"请选择身份证有效期");
        [HUD showErrorMessage:@"请选择身份证有效期"];
        return NO;
    }
    
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:_personalInfoView.deatailAddressStr]) {
        
        NSLog(@"请正确输入用户地址");
        [HUD showErrorMessage:@"请正确输入用户地址"];
        return NO;
    }
    
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:_leftImgstr]) {
        
        NSLog(@"请正确上传身份证图片");
        [HUD showErrorMessage:@"请正确上传身份证图片"];
        return NO;
    }
    
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:_rightImgStr]) {
        
        NSLog(@"请正确上传身份证图片");
        [HUD showErrorMessage:@"请正确上传身份证图片"];
        return NO;
    }
    
    if (![BKUserCodeFormat isNameValid:_personalInfoView.userRealNameStr]) {
        
        NSLog(@"请正确输入用户名");
        [HUD showErrorMessage:@"请正确输入用户名"];
        return NO;
    }
    
    if (![BKUserCodeFormat validateIdentityCard:_personalInfoView.identifiCardIdStr]) {
        
        NSLog(@"请正确输入身份证号");
        [HUD showErrorMessage:@"请正确输入身份证号"];
        return NO;
    }
    
    if (![BKUserCodeFormat stringLengthIsRightWIthRequireMinLength:1 maxLength:50 contentStr:_personalInfoView.deatailAddressStr]) {
        
        NSLog(@"用户详细地址信息不能超过50个字");
        [HUD showErrorMessage:@"用户详细地址信息不能超过50个字"];
        return NO;
    }
    
    return YES;
}


#pragma mark ==========BKUserChoosePhotosViewDelegate========================

-(void)bkUserChoosePhotosView:(BKUserChoosePhotosView *)bkUserChoosePhotosView clickLeftImgTag:(NSInteger)imgTag
{
    [self addImgFromPictureLibrary];
    self.CurrentTag = imgTag;
}

-(void)bkUserChoosePhotosView:(BKUserChoosePhotosView *)bkUserChoosePhotosView clickRightImgTag:(NSInteger)imgTag
{
    
    [self addImgFromPictureLibrary];
    self.CurrentTag = imgTag;
}

//图片选择
//添加图片
-(void)addImgFromPictureLibrary
{
    if (iOSSyStem >= 8.0) {
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self takePhotoSelectImgWithSourceType:UIImagePickerControllerSourceTypeCamera];
            }];
            
            [alert addAction:action1];
        }
        
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self selectImgFromPhotoLibraryMaxImagesCount:1];
        }];
        
        UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:action2];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    } else {
        
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选取", nil];
            [sheet showInView:self.view];
        } else {
            
            UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册中选取", nil];
            [sheet showInView:self.view];
        }
        
    }
    
    
    
}

-(void)takePhotoSelectImgWithSourceType:(UIImagePickerControllerSourceType)surceType
{
    UIImagePickerController *imagePickerController =[[UIImagePickerController alloc]init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.navigationBar.barTintColor = [UIColor whiteColor];
    imagePickerController.sourceType = surceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *icon = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImageWriteToSavedPhotosAlbum(icon,nil,nil,nil);
    [self dealWithImg:icon];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(void)selectImgFromPhotoLibraryMaxImagesCount:(NSInteger)maxImgesCount
{
    TZImagePickerController *imgPickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:maxImgesCount delegate:self];
    [imgPickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> * photos, NSArray *assets, BOOL result) {
        
        for (UIImage *image in photos)
        {
            [self dealWithImg:image];
        }
    }];
    [self presentViewController:imgPickerVc animated:YES completion:nil];
    
}

- (void)dealWithImg:(UIImage *)image{
    
    UIImage * newImg = image;
    CGSize imageSize = image.size;
    imageSize.width = image.size.width / 2;
    imageSize.height = image.size.height / 2;
    CGFloat compressionQuality;
    
    if(image.size.height > 3000 || image.size.width > 3000) {
        compressionQuality = 0.3;
    } else if (image.size.height > 1500 || image.size.width > 1500){
        compressionQuality = 0.5;
    } else {
        compressionQuality = 0.8;
    }
    
    UIImage * img = [self imageWithImage:image scaledToSize:imageSize];
    NSData *data = UIImageJPEGRepresentation(img, compressionQuality);
    [self updateRealNameAuthImgWithData:data imge:newImg];
}

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
    
}

-(void)updateRealNameAuthImgWithData:(NSData *)imgData imge:(UIImage *)imge
{
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI upLoadRealNameAuthImgData:imgData resultBlock:^(id obj, NSError *error) {
        [BKIndicationView dismiss];
        if (obj) {
            
            BKUserRequestResultModel * result = obj;
            if ([result.success isEqualToString:@"1"]) {
                
                if (self.CurrentTag == 1) {
                    
                    self.leftImgstr = result.data;
                    self.leftImg = imge;
                } else{
                    
                    
                    self.rightImgStr = result.data;
                    self.rigthImg = imge;
                }
                
                [HUD showSuccessMessage:result.msg];
            } else {
            
            NSLog(@"实名认证上传图片%@",result.msg);
            NSString * string = result.msg;
            [HUD showErrorMessage:string];
         }
        } else {
            
            NSLog(@"实名认证网络请求失败。。。。。");
            [HUD showErrorMessage:@"网络请求失败"];
        }
    }];
}

-(void)setLeftImg:(UIImage *)leftImg
{
    _leftImg = leftImg;
    self.choosePhotoView.leftImg = _leftImg;
}

-(void)setRigthImg:(UIImage *)rigthImg
{
    _rigthImg = rigthImg;
    self.choosePhotoView.rightImg = _rigthImg;
}

#pragma mark =========================布局===================================

-(void)setUpViews{
    
    _bGScrowView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, self.view.bounds.size.height)];
//    self.bGScrowView.bounces = NO;
    _bGScrowView.showsVerticalScrollIndicator = NO;
    _bGScrowView.showsHorizontalScrollIndicator = NO;
    _bGScrowView.delegate = self;
    [self.view addSubview:_bGScrowView];
   
    _personalInfHeaderView = [[BKUserSectionHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 33) withType:1];
    _personalInfHeaderView.titleStr = @"身份信息";
    _personalInfHeaderView.backgroundColor = RGBCOLOR(242, 242, 242, 1);
    [self.bGScrowView addSubview:_personalInfHeaderView];
   
    _personalInfoView = [[BkRealNamePersonalInfoView alloc]initWithFrame:CGRectMake(0, 33, SCREENWIDTH, 193)];
    _personalInfoView.myDelegate = self;
    [_bGScrowView addSubview:_personalInfoView];
    
    _photosHeaderView =  [[BKUserSectionHeaderView alloc]initWithFrame:CGRectMake(0, 226, SCREENWIDTH, 33) withType:2];
    _photosHeaderView.titleStr = @"身份证正反面照片";
    _personalInfHeaderView.type = 2;
     _personalInfHeaderView.backgroundColor = RGBCOLOR(242, 242, 242, 1);
    [_bGScrowView addSubview:_photosHeaderView];
    
    _choosePhotoView = [[BKUserChoosePhotosView alloc]initWithFrame:CGRectMake(0, 259, SCREENWIDTH, 200)];
    _choosePhotoView.backgroundColor = [UIColor whiteColor];
    _choosePhotoView.myDelegate = self;
    [_bGScrowView addSubview:_choosePhotoView];
    
    CGFloat height = SCREENWIDTH < 350?160.f:130.f;
    _authReasonViews = [[BKRealAuthFailReasonView alloc]initWithFrame:CGRectMake(0, 459, SCREENWIDTH, height)];
    [_bGScrowView addSubview:_authReasonViews];
    
    _commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _commitBtn.top = _authReasonViews.bottom;
    _commitBtn.left = 15;
    _commitBtn.size = CGSizeMake(SCREENWIDTH-30, 50);
    _commitBtn.titleLabel.font = UIFontLargest;
    _commitBtn.backgroundColor = BK_MY_COLOR_01;
    _commitBtn.layer.cornerRadius = 4;
    _commitBtn.layer.masksToBounds = YES;
    [_commitBtn setTitle:@"提交申请" forState:UIControlStateNormal];
    [_commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_bGScrowView addSubview:_commitBtn];
    _bGScrowView.contentSize = CGSizeMake(ScreenWidth,_commitBtn.bottom + 15);
    
    [self creatDatePickView];
    
}


#pragma mark =========================UIDatepicker===================================

-(void)creatDatePickView
{
    UIView * bgView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    self.bgView1 = bgView1;
    self.bgView1.hidden = YES;
    bgView1.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
   
    [window setUserInteractionEnabled:YES];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelSelectDate)];
    tap.delegate = self;
    [bgView1 addGestureRecognizer:tap];
    
    [window addSubview:bgView1];

    UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0,self.view.bounds.size.height, SCREENWIDTH, 340)];
    self.bgView = bgView;
    bgView.backgroundColor = [UIColor whiteColor];
    [window addSubview:bgView];
    
    UIButton * cacelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    cacelBtn.frame = CGRectMake(10, 10, 60, 20);
    //[cacelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cacelBtn.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [cacelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cacelBtn addTarget:self action:@selector(cancelSelectDate) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:cacelBtn];
    
    UIButton * completeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    completeBtn.frame = CGRectMake(SCREENWIDTH-70, 10, 60, 20);
    [completeBtn.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [completeBtn setTitle:@"确定" forState:UIControlStateNormal];
    [completeBtn addTarget:self action:@selector(selectDate) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:completeBtn];
    
    UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0,40, SCREENWIDTH, 226)];
    self.datePick = datePicker;
    datePicker.datePickerMode = UIDatePickerModeDate;//模式选择
    datePicker.date = [NSDate date];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中文
    datePicker.locale = locale;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    [bgView addSubview:datePicker];
    
}

-(void)cancelSelectDate
{
    __weak typeof(self) weakSelf = self;
 
    [UIView animateWithDuration:0.3 animations:^{
        
        weakSelf.bgView .frame = CGRectMake(0, ScreenHeight,SCREENWIDTH, 340);
        
    } completion:^(BOOL finished) {
        
        weakSelf.bgView1.hidden = YES;
        
    }];
    
}

-(void)selectDate
{
    __weak typeof(self) weakSelf = self;
    self.bgView1.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        weakSelf.bgView .frame = CGRectMake(0, ScreenHeight,SCREENWIDTH, 340);
        
    } completion:^(BOOL finished) {
        
        weakSelf.bgView1.hidden = YES;
 
    }];
    
    NSDate *selecDate = [self.datePick  date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    NSString *dateStr = [dateFormatter stringFromDate:selecDate];
    
    self.personalInfoView.availableTimeStr = dateStr;
}

//防止tap 手势 导致collectionView item 点击不响应的问题
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    
    NSLog(@"%@",NSStringFromClass([touch.view.superview class]));
    
    if (self.bgView1.hidden) {
        
        return NO;
    } else {
        
        return YES;
    }
    
}

@end
